package com.mdd.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局的异常处理器
 */

@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     *处理字段相同的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
        if (message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            return R.error(s[2]+"已存在");
        }

        return R.error("未知错误");
    }


    /**
     * 处理自定义异常
     * @param customException
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException customException){
        log.info(customException.getMessage());
        return R.error(customException.getMessage());
    }

}
